import React,{Component} from 'react'
import {
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    ToastAndroid,
    PermissionsAndroid,
} from 'react-native'
import { MapView } from 'react-native-amap3d'
//import {
//    MapView,
//    MapTypes,
//    Geolocation
//} from 'react-native-baidu-map';

const Geolocation = require('Geolocation');

export default class PermissionAndroidView extends Component {
  constructor(props) {
    super(props)
    this.state = { text: "" ,coords:{latitude:0,longitude:0}}
  }
    render() {
        return (
        <View style={{flex:1}}>
            <View style={styles.container}>

                <TouchableOpacity style={styles.button_view}
                    onPress={this.requestLocationPermission.bind(this)}>
                    <Text style={styles.button_text}>申请访问地址权限</Text>
                </TouchableOpacity>
                <TouchableOpacity style={styles.button_view}
                    onPress={this.requestACCESS_COARSE_LOCATION.bind(this)}>
                    <Text style={styles.button_text}>申请服务信号权限</Text>
                </TouchableOpacity>


                <TouchableOpacity style={styles.button_view}
                                  onPress={this.checkPermission.bind(this)}>
                    <Text style={styles.button_text}>查询是否获取了读写权限</Text>
                </TouchableOpacity>
                <TouchableOpacity style={styles.button_view}
                                  onPress={this.requestMultiplePermission.bind(this)}>
                    <Text style={styles.button_text}>一次申请所以权限</Text>
                </TouchableOpacity>

                <TouchableOpacity style={styles.button_view}
                                  onPress={this.checkPermissionGPS.bind(this)}>
                    <Text style={styles.button_text}>获取GPS</Text>
                </TouchableOpacity>

                <Text >addr:{this.state.text},{this.state.coords.latitude},{this.state.coords.longitude}</Text>
            </View>

                <View style={{flex:1}}>
                     { this.renderMap() }
                </View>
            </View>
        )
    }

    renderMap=()=>{
        if (parseInt(this.state.coords.latitude) == 0){
            return (<MapView style={StyleSheet.absoluteFill}/>)
        }else{
           return (
                    <MapView style={StyleSheet.absoluteFill}>
                     <MapView.Marker
                       active
                       title='这是一个标注点'
                       color='red'
                       description='Hello world!'
                       coordinate={{
                         latitude: parseFloat(this.state.coords.latitude),
                         longitude: parseFloat(this.state.coords.longitude),
                       }}
                     />
                   </MapView>
                   )
        }

    }

    show(data) {
        ToastAndroid.show(data,ToastAndroid.SHORT)
    }

    /*
    * 弹出提示框向用户请求某项权限。返回一个promise，最终值为用户是否同意了权限申请的布尔值。
    * 其中rationale参数是可选的，其结构为包含title和message)的对象。
    * 此方法会和系统协商，是弹出系统内置的权限申请对话框，
    * 还是显示rationale中的信息以向用户进行解释。
    * */
    async requestReadPermission() {
        try {
            //返回string类型
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
                {
                    //第一次请求拒绝后提示用户你为什么要这个权限
                    'title': '我要读写权限',
                    'message': '没权限我不能工作，同意就好了'
                }
            )
            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                this.show("你已获取了读写权限")
            } else {
                this.show("获取读写权限失败")
            }
        } catch (err) {
            this.show(err.toString())
        }
    }

        async requestACCESS_COARSE_LOCATION() {
            try {
                //返回string类型
                const granted = await PermissionsAndroid.request(

                    PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
                    {
                        //第一次请求拒绝后提示用户你为什么要这个权限
                        'title': '我要服务信号',
                        'message': '没权限我不能工作，同意就好了'
                    }
                )
                if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                    this.show("你已获取了服务信号权限")
                } else {
                    this.show("获取服务信号权限失败")
                }
            } catch (err) {
                this.show(err.toString())
            }
        }



    async requestCarmeraPermission() {
        try {
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.CAMERA,
                {
                    //第一次请求拒绝后提示用户你为什么要这个权限
                    'title': '我要相机权限',
                    'message': '没权限我不能工作，同意就好了'
                }
            )
            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                this.show("你已获取了相机权限")
            } else {
                this.show("获取相机失败")
            }
        } catch (err) {
            this.show(err.toString())
        }
    }

    async requestLocationPermission() {
        try {
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                {
                    //第一次请求拒绝后提示用户你为什么要这个权限
                    'title': '我要地址查询权限',
                    'message': '没权限我不能工作，同意就好了'
                }
            )

            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                this.show("你已获取了地址查询权限")
            } else {
                this.show("获取地址查询失败")
            }
        } catch (err) {
            this.show(err.toString())
        }
    }

    checkPermission() {
        try {
            //返回Promise类型
            const granted = PermissionsAndroid.check(
                PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
            )
            granted.then((data)=>{
                this.show("是否获取读写权限"+data)
            }).catch((err)=>{
                this.show(err.toString())
            })
        } catch (err) {
            this.show(err.toString())
        }
    }

    checkPermissionGPS() {
            try {
                //返回Promise类型
                const granted = PermissionsAndroid.check(
                    PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
                )
                granted.then((data)=>{
                    this.show("是否获取GPS权限"+data)
                    if (data){
                        this.getLocation()
                    }else{
                        this.show("还没有权限，请点击按钮申请")
                    }
                }).catch((err)=>{
                    this.show(err.toString())
                })
            } catch (err) {
                this.show(err.toString())
            }
        }

   getLocation=()=> {
      Geolocation.getCurrentPosition(
          location => {
              var result = "速度：" + location.coords.speed +
                          "\n经度：" + location.coords.longitude +
                          "\n纬度：" + location.coords.latitude +
                          "\n准确度：" + location.coords.accuracy +
                          "\n行进方向：" + location.coords.heading +
                          "\n海拔：" + location.coords.altitude +
                          "\n海拔准确度：" + location.coords.altitudeAccuracy +
                          "\n时间戳：" + location.timestamp;
                            this.show(result)


                url=this.props.maptype=="baidu" ? this.props.url+location.coords.latitude+','+location.coords.longitude : this.props.url+location.coords.longitude+','+location.coords.latitude

                    fetch(url)
                      .then((response) => response.json())
                      .then((responseJson) => {
//                           this.show("info:\n"+responseJson.result.addressComponent)
//                           this.show("info:\n"+responseJson.regeocode)
                            this.setState({
                                    text: this.props.maptype=="baidu"? responseJson.result.formatted_address : responseJson.regeocode.formatted_address,
//                                    text:url,
                                    coords:location.coords
                            })
                      })
                      .catch((error) =>{
                            this.show("request baidu MAP err:",err)
                      });
          },
          error => {
            this.show("获取位置失败："+ error)
          },
//          {enableHighAccuracy: true, timeout: 200000, maximumAge: 10000}
      );
   }



    async requestMultiplePermission() {
        try {
            const permissions = [
                PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
                PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                PermissionsAndroid.PERMISSIONS.CAMERA
            ]
            //返回得是对象类型
            const granteds = await PermissionsAndroid.requestMultiple(permissions)
            var data = "是否同意地址权限: "
            if (granteds["android.permission.ACCESS_FINE_LOCATION"] === "granted") {
                data = data + "是\n"
            } else {
                data = data + "否\n"
            }
            data = data+"是否同意相机权限: "
            if (granteds["android.permission.CAMERA"] === "granted") {
                data = data + "是\n"
            } else {
                data = data + "否\n"
            }
            data = data+"是否同意存储权限: "
            if (granteds["android.permission.WRITE_EXTERNAL_STORAGE"] === "granted") {
                data = data + "是\n"
            } else {
                data = data + "否\n"
            }
            this.show(data)
        } catch (err) {
            this.show(err.toString())
        }
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        padding: 10,
    },
    button_view: {
        margin:4,
        borderRadius: 4,
        backgroundColor: '#8d4dfc',
        alignItems: 'center',
    },
    button_text: {
        padding: 6,
        fontSize: 16,
        fontWeight: '600'
    }
})
